<?php
class Pldkp_Db_Table_Abstract extends Zend_Db_Table_Abstract 
{
    /**
     * Curently being used to magically get rows by key and values.
     * 
     * @param string $name
     * @param array $arguments
     */
    public static function __callStatic($name, $arguments)
    {
        if (strpos($name, 'getBy') === 0 && count($arguments) > 0) {
            $getBy = lcfirst(substr($name, 5));
            return self::getBy($getBy, $arguments[0]);
        } elseif (strpos($name, 'getAllBy') === 0 && count($arguments) > 0) {
            $getBy = lcfirst(substr($name, 8));
            return self::getAllBy($getBy, $arguments[0]);
        } 
        
        throw new Exception('Unknown __callStatic: "' . $name . '" on class "' . get_called_class() . '" with arguments: ' . implode(',', $arguments));
    }
    
    /**
     * Returns a new blank instance of the row class to be 
     * used for inserting.
     * 
     * @return Zend_Db_Table_Row_Abstract
     */
    public static function getNew()
    {
        // Create static self
        $className = get_called_class();
        $table = new $className();
        return $table->fetchNew();
    }
    
    /**
     * Get all rows for this table.
     * 
     * @return Zend_Db_Table_Rowset_Abstract
     */
    public static function getAll()
    {
        // Create static self
        $className = get_called_class();
        $table = new $className();
        return $table->fetchAll();
    }
    
    /**
     * Will return all rows matching the key and value as a 
     * rowset.
     * 
     * @param string $key
     * @param string $value
     * @return Zend_Db_Table_Rowset_Abstract
     */
    public static function getAllBy($key, $value)
    {
        // Create static self
        $className = get_called_class();
        $table = new $className();
        // Create a select
        $select = $table->select()->where($key .' = ?', $value);
        $rows = $table->fetchAll($select);
        return $rows;
    }
    
    /**
     * Will return a single row matching the the key and value.
     * 
     * @param string $key
     * @param string $value
     * @return Zend_Db_Table_Row_Abstract|null
     */
    public static function getBy($key, $value)
    {
        if ($value === null) {
            return null;
        }
        // Create static self
        $className = get_called_class();
        $table = new $className();
        // Create a select
        $select = $table->select()->where($key .' = ?', $value);
        $row = $table->fetchRow($select);
        return $row;
    }
}